package com.streamer.app.utils.camera2

import android.annotation.SuppressLint
import android.content.Context
import android.hardware.camera2.CameraAccessException
import android.hardware.camera2.CameraCaptureSession
import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.CameraDevice
import android.hardware.camera2.CameraManager
import android.hardware.camera2.CaptureRequest
import android.media.ImageReader
import android.os.Handler
import android.os.HandlerThread
import android.util.Log
import android.view.Surface
import android.view.WindowManager
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity


class PhoneCameraManager(
    val mContext: AppCompatActivity
) {
    private var cameraDevice: CameraDevice? = null
    private var captureRequestBuilder: CaptureRequest.Builder? = null
    private var cameraCaptureSession: CameraCaptureSession? = null
    private var cameraId = "0"
    private var displays: MutableList<Surface>? = null

    fun setDisplayTarget(targets: MutableList<Surface>, previewWidth: Int, previewHeight: Int, cameraId: String) {
        releaseSurfaces()
        displays = targets
        createImageReader(previewWidth, previewHeight)
        imageReader?.let {
            displays?.add(it.surface)
        }
        if (this.cameraId != cameraId) {
            this.cameraId = cameraId
            destory()
        }
        createCameraPreviewSession()
    }


    /**
     * 销毁所有surface
     */
    private fun releaseSurfaces() {
        // 不要主动释放来自外部（如SurfaceView/TextureView）的Surface，避免被标记为 abandoned
        displays?.clear()
        displays = null
        imageReader?.close()
        imageReader = null
    }

    /**
     * 切换摄像头
     */
    fun setCameraId(cameraId: String, isAutoCreateDevice: Boolean = true) {
        if (this.cameraId != cameraId) {
            this.cameraId = cameraId
            if (cameraDevice != null) {
                stopPreView()
                cameraCaptureSession?.close()
                cameraCaptureSession = null
                cameraDevice?.close()
                cameraDevice = null
                if (isAutoCreateDevice) {
                    openCamera()
                }
            }
        }

    }

    /**
     *
     */
    fun destory() {
        try {
            stopPreView()
            cameraCaptureSession?.close()
            cameraCaptureSession = null
            cameraDevice?.close()
            cameraDevice = null
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    @SuppressLint("MissingPermission")
    fun openCamera() {
        val manager = mContext.getSystemService(Context.CAMERA_SERVICE) as CameraManager
        try {
            manager.openCamera(cameraId, object : CameraDevice.StateCallback() {
                override fun onOpened(camera: CameraDevice) {
                    cameraDevice = camera
                    createCameraPreviewSession()
                }

                override fun onDisconnected(camera: CameraDevice) {
                    camera.close()
                }

                override fun onError(camera: CameraDevice, error: Int) {
                    camera.close()
                    cameraDevice = null
                }
            }, null)
        } catch (e: CameraAccessException) {
            e.printStackTrace()
        }
    }

    @Synchronized
    private fun createCameraPreviewSession() {
        closeSession()
        if (cameraDevice == null) {
            openCamera()
            return
        }
        // 没有合法的显示目标则不创建Session
        val targets = displays
        if (targets.isNullOrEmpty()) return
        try {
            val characteristics = (mContext.getSystemService(Context.CAMERA_SERVICE) as CameraManager)
                .getCameraCharacteristics(cameraId)
            val sensorRect = characteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE)
                ?: throw IllegalStateException("Unable to get sensor info")

            cameraDevice!!.createCaptureSession(
                targets,
                object : CameraCaptureSession.StateCallback() {
                    override fun onConfigured(session: CameraCaptureSession) {
                        if (cameraDevice == null) {
                            return
                        }
                        cameraCaptureSession = session
                        sendCaptureRequest()
                    }

                    override fun onConfigureFailed(session: CameraCaptureSession) {

                    }
                },
                null
            )
        } catch (e: CameraAccessException) {
            e.printStackTrace()
        }
    }
    


    fun reUpdate() {
        sendCaptureRequest()

    }

    private var imageReader: ImageReader? = null

    private fun createImageReader(width: Int, height: Int) {
        // 这里如果需要抓帧可创建ImageReader；否则保持为null即可
        // 如需启用，取消注释并选择合适的格式和大小
        // imageReader = ImageReader.newInstance(width.coerceAtLeast(1), height.coerceAtLeast(1), ImageFormat.YUV_420_888, 2)
        imageReader?.setOnImageAvailableListener({ reader ->
            val image = reader.acquireLatestImage()
            if (image != null) {
                image.close()
            }
        }, createBackgroundHander())

    }

    /**
     * 创建异步handler
     */
    private fun createBackgroundHander(): Handler {
        val handlerThread = HandlerThread("phoneCamer${System.currentTimeMillis()}")
        handlerThread.start()
        return Handler(handlerThread.looper)
    }

    /**
     * 停止预览
     */
    fun stopPreView() {
        if (cameraCaptureSession == null) return
        cameraCaptureSession?.stopRepeating()
        cameraCaptureSession?.abortCaptures()
    }

    private fun closeSession() {
        try {
            stopPreView()
            cameraCaptureSession?.close()
            cameraCaptureSession = null
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }


    /**
     * 发生请求
     */
    private fun sendCaptureRequest() {
        if (cameraDevice == null) {
            return
        }
        val targets = displays
        if (targets.isNullOrEmpty()) return
        try {
            captureRequestBuilder =
                cameraDevice?.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW)
            captureRequestBuilder?.apply {
                targets.forEach {
                    addTarget(it)
                }
                set(CaptureRequest.CONTROL_MODE, CaptureRequest.CONTROL_MODE_AUTO)//设置自动曝光，自动白平衡，自动对焦
                val rotate = getRotationCompensation()
                Log.e("xxxxxxx", "====补偿角度======$rotate")
                set(CaptureRequest.JPEG_ORIENTATION, rotate)
                

                
                cameraCaptureSession?.setRepeatingRequest(
                    build(),
                    null,
                    createBackgroundHander()
                )
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

  private  fun getRotationCompensation(): Int {
        val cameraManager = mContext.getSystemService(Context.CAMERA_SERVICE) as CameraManager
        return try {
            val characteristics = cameraManager.getCameraCharacteristics(cameraId)
            val sensorOrientation = characteristics[CameraCharacteristics.SENSOR_ORIENTATION]!!
            val windowManager = mContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager
            val deviceRotation: Int = windowManager.defaultDisplay.rotation
            val rotationDegrees: Int = when (deviceRotation) {
                Surface.ROTATION_0 -> 0
                Surface.ROTATION_90 -> 90
                Surface.ROTATION_180 -> 180
                Surface.ROTATION_270 -> 270
                else -> 0
            }
            (sensorOrientation + rotationDegrees) % 360
        } catch (e: CameraAccessException) {
            e.printStackTrace()
            0
        }
    }


}